package db

import (
	"context"
	"github.com/redis/go-redis/v9"
	"github.com/zeromicro/go-zero/core/logx"
	"payme3000/framework/errorx"
	"strings"
	"sync"
)

var (
	redisLock sync.RWMutex
	redisMap  = map[Type]redis.UniversalClient{}
)

func GetRedis(dbType Type) redis.UniversalClient {
	redisLock.RLock()
	defer redisLock.RUnlock()

	return redisMap[dbType]
}

func CreateRedis(dbType Type, config *Config) error {
	redisLock.Lock()
	defer redisLock.Unlock()

	// 锁定后再检查一次
	if client := redisMap[dbType]; client != nil {
		return nil
	}

	if config.ReplicaSet != "" { // redis是集群
		redisMap[dbType] = redis.NewClusterClient(
			&redis.ClusterOptions{
				Addrs:    strings.Split(config.Host, ","),
				Username: config.Username,
				Password: config.Password,
				PoolSize: 8,
			})
	} else { // redis是单机
		redisMap[dbType] = redis.NewClient(&redis.Options{
			Addr:     config.Host,
			Username: config.Username,
			Password: config.Password,
			DB:       0,
			PoolSize: 8,
		})
	}

	logx.Infof("create redis done with dbType:%d, host:%s, db:%s", dbType, config.Host, config.Db)

	return nil
}

func StopRedis() {
	redisLock.RLock()
	defer redisLock.RUnlock()

	for _, _redis := range redisMap {
		errorx.Catch(context.Background(), _redis.Close())
	}
}
